package com.oceanstar.service.Impl;

import com.oceanstar.Pojo.*;
import com.oceanstar.mapper.DiseaseStatsMapper;
import com.oceanstar.service.IDiseaseStatsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class DiseaseStatsServiceImpl implements IDiseaseStatsService {

    private final DiseaseStatsMapper diseaseStatsMapper;

    public DiseaseStatsServiceImpl(DiseaseStatsMapper diseaseStatsMapper) {
        this.diseaseStatsMapper = diseaseStatsMapper;
    }

    @Override
    public DiseaseSummaryDTO getDiseaseSummary(DiseaseStatsQuery query) {
        // 参数处理
        processQueryParams(query);

        DiseaseSummaryDTO summary = new DiseaseSummaryDTO();

        // 统计基础数据 - 传入查询条件
        Integer totalElderly = diseaseStatsMapper.countTotalElderly(query);
        Integer majorDiseaseElderly = diseaseStatsMapper.countMajorDiseaseElderly(query);
        Integer newCasesLast30Days = diseaseStatsMapper.countNewCasesLast30Days(query);

        summary.setTotalElderly(totalElderly);
        summary.setMajorDiseaseElderly(majorDiseaseElderly);
        summary.setMajorDiseaseRate(totalElderly > 0 ? Double.parseDouble(String.format("%.4f", (double) majorDiseaseElderly / totalElderly)) : 0.0);
        summary.setNewCasesLast30Days(newCasesLast30Days);

        // 疾病类型统计 - 传入查询条件
        List<DiseaseSummaryDTO.DiseaseStat> diseaseStats = diseaseStatsMapper.selectDiseaseStats(query);
        if (majorDiseaseElderly > 0) {
            diseaseStats.forEach(stat -> {
                double rate = (double) stat.getCount() / majorDiseaseElderly;
                stat.setRate(Double.parseDouble(String.format("%.4f", rate)));
            });
        }
        summary.setDiseaseStats(diseaseStats);

        // 年龄段统计 - 传入查询条件
        summary.setAgeStats(diseaseStatsMapper.selectAgeStats(query));

        // 性别统计 - 传入查询条件
        summary.setGenderStats(diseaseStatsMapper.selectGenderStats(query));

        // 趋势统计
        DiseaseSummaryDTO.DiseaseTrend trend = generateDiseaseTrend(query);
        summary.setTrend(trend);

        return summary;
    }
    // 趋势统计方法
    private DiseaseSummaryDTO.DiseaseTrend generateDiseaseTrend(DiseaseStatsQuery query) {
        DiseaseSummaryDTO.DiseaseTrend trend = new DiseaseSummaryDTO.DiseaseTrend();

        // 1. 确定时间范围
        String startMonth;
        String endMonth;

        // 如果前端传入了时间范围，则使用前端的时间范围
        if (query.getBegin() != null && query.getEnd() != null) {
            startMonth = query.getBegin().substring(0, 7) + "-01"; // 转换为月初
            endMonth = query.getEnd().substring(0, 7) + "-01";     // 转换为月初
        } else {
            // 前端没有传时间时，查询数据库最早记录到当前时间
            Map<String, String> timeRange = diseaseStatsMapper.selectTimeRange(query);
            startMonth = timeRange.get("start_month");
            endMonth = timeRange.get("end_month");

            // 如果数据库没有数据，使用默认范围（从最早可能时间到当前月）
            if (startMonth == null || endMonth == null) {
                // 设置为合理的默认范围，比如从5年前到当前月
                LocalDate defaultStart = LocalDate.now().minusYears(5);
                startMonth = defaultStart.format(DateTimeFormatter.ofPattern("yyyy-MM-01"));
                endMonth = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-01"));
            } else {
                // 确保结束时间是当前月（如果数据库最新数据是之前的月份）
                LocalDate dbEndDate = LocalDate.parse(endMonth);
                LocalDate currentMonth = LocalDate.now().withDayOfMonth(1);
                if (dbEndDate.isBefore(currentMonth)) {
                    endMonth = currentMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-01"));
                }
            }
        }

        // 2. 在Java中生成完整的时间线
        List<String> monthStarts = generateMonthRange(startMonth, endMonth);

        List<String> timeline = new ArrayList<>();
        List<Integer> newCases = new ArrayList<>();
        List<Integer> totalWithDisease = new ArrayList<>();

        // 3. 为每个月份查询数据
        for (String monthStart : monthStarts) {
            timeline.add(monthStart);

            Integer newCaseCount = diseaseStatsMapper.selectNewCasesByMonth(monthStart, query);
            newCases.add(newCaseCount != null ? newCaseCount : 0);

            Integer totalCount = diseaseStatsMapper.selectTotalWithDiseaseByMonth(monthStart, query);
            totalWithDisease.add(totalCount != null ? totalCount : 0);
        }

        trend.setTimeline(timeline);
        trend.setNewCases(newCases);
        trend.setTotalWithDisease(totalWithDisease);

        return trend;
    }
    // 在Java中生成月份范围
    private List<String> generateMonthRange(String startMonth, String endMonth) {
        List<String> months = new ArrayList<>();

        LocalDate start = LocalDate.parse(startMonth);
        LocalDate end = LocalDate.parse(endMonth);

        LocalDate current = start;
        while (!current.isAfter(end)) {
            months.add(current.format(DateTimeFormatter.ofPattern("yyyy-MM-01")));
            current = current.plusMonths(1);
        }

        return months;
    }

    @Override
    public DiseaseHeatmapDTO getDiseaseHeatmap(DiseaseHeatmapQuery query) {
        // 参数验证
        if (query.getLevel() == null) {
            query.setLevel("community");
        }
        if (query.getMetric() == null) {
            query.setMetric("rate");
        }

        DiseaseHeatmapDTO result = new DiseaseHeatmapDTO();
        result.setMetric(query.getMetric());

        // 调用Mapper
        List<DiseaseHeatmapDTO.RegionStat> rows = diseaseStatsMapper.selectRegionStats(query);

        // 计算患病率
        for (DiseaseHeatmapDTO.RegionStat regionStat : rows) {
            regionStat.setCount(regionStat.getElderlyCount());
            if (regionStat.getElderlyCount() != null && regionStat.getElderlyCount() > 0) {
                double rate = (double) regionStat.getMajorDiseaseCount() / regionStat.getElderlyCount();
                regionStat.setRate(rate);  // 直接赋值double，不需要parseDouble
            } else {
                regionStat.setRate(0.0);
            }
        }

        result.setRows(rows);
        result.setTotal(rows.size());

        return result;
    }

    private void processQueryParams(DiseaseStatsQuery query) {
        // 处理日期范围
        if (query.getBegin() == null || query.getBegin().trim().isEmpty()) {
            query.setBegin(null);
        }
        if (query.getEnd() == null || query.getEnd().trim().isEmpty()) {
            query.setEnd(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        }

        // 处理疾病名称
        if (query.getDiseaseNames() != null && !query.getDiseaseNames().trim().isEmpty()) {
            List<String> diseaseList = Arrays.stream(query.getDiseaseNames().split(","))
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .collect(Collectors.toList());
            query.setDiseaseList(diseaseList);
        } else {
            List<String> majorDiseases = diseaseStatsMapper.selectMajorDiseaseList();
            query.setDiseaseList(majorDiseases);
        }

        // 处理年龄范围验证
        if (query.getMinAge() != null && query.getMaxAge() != null) {
            if (query.getMinAge() > query.getMaxAge()) {
                throw new IllegalArgumentException("最小年龄不能大于最大年龄");
            }
        }
    }
}